package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.demo.utils.PageVo;
import com.example.demo.entity.UserInfo;
import com.example.demo.service.UserInfoService;
import com.example.demo.utils.ResultCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author LF
 * @date 2021/4/20 - 10:15
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserInfoController {

    @Autowired
    private UserInfoService service;

    @GetMapping("/getAll")
    public List<UserInfo> getAll(){
        List<UserInfo> userInfoList = service.list();
        userInfoList.forEach(System.out::println);
        return userInfoList;
    }

    @GetMapping("/getPage")
    public ResultCode getPage(int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfo> userInfoList = service.list();
        PageInfo<UserInfo> page = new PageInfo<>(userInfoList);
        PageVo pageVo = new PageVo(page, pageNum);
        return new ResultCode(200, "执行成功", pageVo);
    }

    /**
     * Aop异常测试
     * @return
     */
    @GetMapping("/getTest")
    public ResultCode getTest(){
        try {
            int num = 1/0;
            log.info(String.valueOf(num));
        }catch(ArithmeticException e){
            throw new ArithmeticException("java.lang.ArithmeticException: / by zero");
        }
        return new ResultCode(200, "执行成功");
    }

    @GetMapping("/getUserInfo/{id}")
    public UserInfo getUserInfoById(@PathVariable("id") Long id){
        UserInfo userInfo = service.getById(id);
        return userInfo;
    }

    /**
     * {
     *     "useNo": 100003,
     *     "useName": "韩信",
     *     "mobile": 15699996666,
     *     "sex": "0",
     *     "age": 22,
     *     "nativePlace": 9535268253,
     *     "idCard": 518685208485851
     * }
     * @param userInfo
     * @return
     */
    @PostMapping("/add")
    public UserInfo save(@RequestBody UserInfo userInfo){
        service.save(userInfo);
        return userInfo;
    }

    @PutMapping("/update")
    public UserInfo update(@RequestBody UserInfo userInfo){
        //service.saveOrUpdate(userInfo);
        //service.updateById(userInfo);
        //更新指定字段
        LambdaUpdateWrapper<UserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserInfo::getUseId, userInfo.getUseId())
        .set(UserInfo::getAge, 99);
        service.update(null, lambdaUpdateWrapper);
        userInfo.setAge(99);
        return userInfo;
    }

    @DeleteMapping("/delete/{id}")
    public ResultCode delete(@PathVariable("id") Long id){
        service.removeById(id);
        return new ResultCode(200, "执行成功");
    }
}
